package com.cvte.sunkit.tools

import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.regex.Matcher
import java.util.regex.Pattern
import kotlin.math.pow
import kotlin.math.round


object IOTool {
    private const val TAG = "IOTool"

    private var mLastIn = 0L
    private var mLastOut = 0L
    private var mCurrentIn = 0L
    private var mCurrentOut = 0L


    /**
     * pgpgin 单位为页面
     * 每个页面  4kb
     */
    private const val PAGE_SIZE = 4

    /**
     * 读取/proc/vmstat
     */
    private fun loadTotalLine() {
        val command = "cat /proc/vmstat | grep pgpg"
        var process: Process? = null
        var reader: BufferedReader? = null
        var line: String?
        try {
            process = Runtime.getRuntime().exec(command)
            reader = BufferedReader(InputStreamReader(process.inputStream))
            var key: String
            var value: String
            val pattern: Pattern = Pattern.compile("^(pgpgin|pgpgout)\\s+(\\d+)")
            while (reader.readLine().also { line = it } != null) {
                val matcher: Matcher = pattern.matcher(line)
                if (matcher.find()) {
                    key = matcher.group(1)
                    value = matcher.group(2)
                    if (key == "pgpgin") { // in数据
                        mCurrentIn = value.toLong()
                    } else { // out数据
                        mCurrentOut = value.toLong()
                    }
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            reader?.close()
            process?.destroy()
        }
    }

    @JvmStatic
    fun getIOInAndOut(): List<Double> {
        loadTotalLine()
        return if (mLastIn == 0L || mLastOut == 0L) {
            mLastOut = mCurrentOut
            mLastIn = mCurrentIn
            mutableListOf(0.0, 0.0)
        } else {
            val inSpeed = (mCurrentIn - mLastIn) * PAGE_SIZE /1024 // kb转化为mb
            val outSpeed = (mCurrentOut - mLastOut) * PAGE_SIZE /1024
            val multiplier = 10.0.pow(2)
            mLastOut = mCurrentOut
            mLastIn = mCurrentIn
            mutableListOf(
                round(inSpeed * multiplier) / multiplier,
                round(outSpeed * multiplier) / multiplier
            )
        }
    }
}